package com.sumainfor.pc.epc.service.impl;

import com.google.common.collect.Lists;
import com.google.common.collect.Maps;
import com.sumainfor.common.Constants;
import com.sumainfor.common.util.ContextUtils;
import com.sumainfor.common.util.CustomMap;
import com.sumainfor.common.util.JsonResult;
import com.sumainfor.common.utlis.ComUtils;
import com.sumainfor.common.utlis.HtmlUtil;
import com.sumainfor.common.utlis.Pager;
import com.sumainfor.common.utlis.ParamsCommon;
import com.sumainfor.pc.epc.dao.DecoratedBeingMapper;
import com.sumainfor.pc.epc.dao.DecorateplanMapper;
import com.sumainfor.pc.epc.dao.UtilsMapper;
import com.sumainfor.pc.epc.feign.GetUserInfoFeign;
import com.sumainfor.pc.epc.feign.Housingauditfeign;
import com.sumainfor.pc.epc.feign.Zfeign.ZzuulFeign;
import com.sumainfor.pc.epc.service.DecoratedBeingService;
import org.apache.commons.collections.MapUtils;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;
import org.springframework.transaction.interceptor.TransactionAspectSupport;

import java.awt.*;
import java.text.SimpleDateFormat;
import java.util.*;
import java.util.List;
import java.util.concurrent.locks.ReentrantLock;

@Service
public class DecoratedBeingServiceImpl implements DecoratedBeingService {

    private ReentrantLock lock = new ReentrantLock(false);

    Logger log = LoggerFactory.getLogger(DecoratedBeingServiceImpl.class);


    @Autowired
    DecoratedBeingMapper mapper;

    @Autowired
    private DecorateplanMapper mapper1;

    @Autowired
    Housingauditfeign housingauditfeign;

    @Autowired
    DecoratedBeingMapper BeingMapper;

    @Autowired
    UtilsMapper utilsMapper;

    @Autowired
    GetUserInfoFeign getUserInfoFeign;

    @Autowired
    private ZzuulFeign feign;

    /**
     * 按条件批次id 和房源装修状态查询房源
     *
     * @param params
     * @return
     */
    @Override
    public JsonResult getDecoratePlanInfo(Map<String, Object> params) {
        JsonResult result = new JsonResult();
        /**
         * 加锁操作
         */
        lock.lock();
        try {
            Map<String, Object> resmap = new HashMap<String, Object>();
            List<Map<String, Object>> datamaolist = mapper.getDecoratePlanInfo(params);
            if (datamaolist.size() > 0) {
                Map<String, Object> maplist = new HashMap<String, Object>();
                maplist.put("datamaolist", datamaolist);
                JsonResult reslist = housingauditfeign.getDecoratePlanInfoResult(maplist);//查询装修中的房源
                List<Map<String, Object>> mapList = (List<Map<String, Object>>) reslist.get("result");//获取集合
                resmap.put("being", mapList);
            } else {
                resmap.put("being", new ArrayList<Map<String, Object>>());
            }
            /////////////////////////
            Map<String, Object> parans1 = new HashMap<String, Object>();
            parans1.put("PlanId", params.get("PlanId").toString());
            parans1.put("State", 2);//查询装修完成的
            List<Map<String, Object>> wanclist = mapper.getDecoratePlanInfo(parans1);
            if (wanclist.size() > 0) {
                Map<String, Object> wancmap = new HashMap<String, Object>();
                wancmap.put("datamaolist", wanclist);
                JsonResult reslist1 = housingauditfeign.getDecoratePlanInfoResult(wancmap);//查询装修中的房源
                List<Map<String, Object>> stocks = (List<Map<String, Object>>) reslist1.get("result");//获取集合
                resmap.put("stocks", stocks);
            } else {
                resmap.put("stocks", new ArrayList<Map<String, Object>>());
            }
            ////////////
            resmap.put("housingPlanInfo", mapper1.getSumhousingPlanInfo(params));//询配置清单
            ////////// 其他费用录入的
            //按照批次id 查询出所有的参与计划的房源
            List<Map<String, Object>> qitalist = mapper.getDecoratePlanInfo1(params);
            if (qitalist.size() > 0) {
                Map<String, Object> postmap = new HashMap<String, Object>();
                List<Map<String, Object>> datalist = new ArrayList<Map<String, Object>>();
                for (Map<String, Object> objectMap : qitalist) {
                    Map<String, Object> qimap = new HashMap<String, Object>();
                    qimap.putAll(objectMap);
                    Map<String, Object> c = mapper.getDepType(objectMap.get("HouId").toString());
                    qimap.put("cou", c.get("cou"));//查询出是否录入了其他费用
                    qimap.put("IfStatus", mapper.getIfStatus(objectMap.get("HouId").toString()));//查询已确认的其他费用
                    qimap.put("IfRest", mapper.getIfRest(objectMap.get("HouId").toString()));//查询修改的其他费用
                    datalist.add(qimap);
                }
                postmap.put("datalist", datalist);//
                JsonResult reslist = housingauditfeign.postmap(postmap);//查询装修中的房源
                List<Map<String, Object>> mapList = (List<Map<String, Object>>) reslist.get("result");//获取集合
                resmap.put("qitainfo", mapList);
            } else {
                resmap.put("qitainfo", new ArrayList<Map<String, Object>>());
            }
            result.put(resmap);
        } catch (Exception e) {
            result.putFailed("服务器繁忙...");
        } finally {
            lock.unlock();//解锁
        }
        return result;
    }

    @Override
    public JsonResult getplan_info_building(Map<String, Object> params, Pager pager) {

        try {

            params.put("SysUserId", ContextUtils.getUserId());//获得管家id
            List<Map<String, Object>> datalist = mapper.getplan_info_building(params);
            List<Map<String, Object>> datalist1 = new ArrayList<Map<String, Object>>();
            for (Map<String, Object> objectMap : datalist) {

                SimpleDateFormat sdf = new SimpleDateFormat("yyyy-mm-dd");
                sdf.format(new Date());//获取当前时间
                Date d1 = sdf.parse(objectMap.get("CheckNoticeTime").toString());
                Date d2 = sdf.parse(sdf.format(new Date()));

                long daysBetween = (d2.getTime() - d1.getTime() + 1000000) / (60 * 60 * 24 * 1000);//逾期天数
                objectMap.put("yuqi", daysBetween);
                datalist1.add(objectMap);
            }

            Map<String, Object> pa = new HashMap<String, Object>();
            log.info("datalist===>" + datalist1);
            if (datalist.size() != 0) {
                pa.put("datalist", datalist1);
            } else {
                pa.put("datalist", new ArrayList<Map<String, Object>>());
            }
            pa.putAll(params);
            return housingauditfeign.gethousingByids(pa, pager);

        } catch (Exception e) {


        }
        return null;
    }

    @Override
    public JsonResult updateInspectStateBy(Map<String, Object> params) {
        JsonResult result = new JsonResult();

        //判断装修计划是否完成
        boolean isSuccess = false;

        if ("1".equals(params.get("insexshow").toString())) {//
            SimpleDateFormat df = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");//设置日期格式
            // new Date()为获取当前系统时间
            params.put("InspectTime", df.format(new Date()));
            params.put("by", ContextUtils.getUserId());//操作人
            params.put("term", "3");// 创建端 Insert端： 1 租客端 2市场部 3 工程部   4运营部   5财务部  6总经办 7发展部
            params.put("fnc", "updateInspectStateBy");// 创建Function名
            ParamsCommon.commonUpdateParms(params);
            //表示是房源配置的验房
            if (mapper.updateInspectStateBy(params) > 0) {

                if ("2".equals(params.get("InspectState").toString())) {
                    params.put("IfCheckState", 1);
                    params.put("CheckStatus", 2);

                    mapper.updateIfCheckStatea(params);
                } else {

                    if (BeingMapper.countInspectState(params) == 0 && BeingMapper.countIfCheckState(params) == 0 && BeingMapper.plan_building(params) == 0) {
                        params.put("IfCheckState", 0);
                        params.put("CheckStatus", 3);
                        mapper.updateIfCheckStatea(params);

                    }


                    if (BeingMapper.countInspectState(params) == 0 && BeingMapper.countIfCheckState(params) == 0 && BeingMapper.plan_building(params) == 0 && BeingMapper.isCourests(params) == 0) {


                        params.put("CheckRealityTime", df.format(new Date()));
                        params.put("CheckState", 2);
                        if (BeingMapper.updateCheckState(params) > 0) {
                            params.put("State", 7);
                            housingauditfeign.updatehousingByHousId(params);//修改房源状态
                            movement(params);//如果这个房源验房全部通过了之后 把工程部里面的配置数据全部移到市场部的房源配置表里面去
                            if (BeingMapper.getCheckStateinfo(params) == 0) {
                                BeingMapper.updatedecorate_plan(params);//当着一批的所有房源全部完成之后自动的改变这个批次的状态
                                isSuccess = true;

                            }
                            //result.putSuccess("操作成功");
                        } else {
                            //  result.putFailed("操作失败");
                        }


                    }
                }
                result.putSuccess("操作成功");

            } else {
                result.putFailed("操作失败");

            }
        } else if ("2".equals(params.get("insexshow").toString())) {
            SimpleDateFormat df = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");//设置日期格式
            // new Date()为获取当前系统时间
            params.put("InspectTime", df.format(new Date()));
            params.put("by", ContextUtils.getUserId());//操作人
            params.put("term", "3");// 创建端 Insert端： 1 租客端 2市场部 3 工程部   4运营部   5财务部  6总经办 7发展部
            params.put("fnc", "updateInspectStateBy");// 创建Function名
            ParamsCommon.commonUpdateParms(params);

            if (mapper.updayeplan_building(params) > 0) {
                if ("2".equals(params.get("InspectState").toString())) {
                    params.put("IfCheckState", 1);
                    params.put("CheckStatus", 2);
                    mapper.updateIfCheckStatea(params);
                } else {

                    if (BeingMapper.countInspectState(params) == 0 && BeingMapper.countIfCheckState(params) == 0 && BeingMapper.plan_building(params) == 0) {
                        params.put("IfCheckState", 0);
                        params.put("CheckStatus", 3);
                        mapper.updateIfCheckStatea(params);

                    }
                    if (BeingMapper.countInspectState(params) == 0 && BeingMapper.countIfCheckState(params) == 0 && BeingMapper.plan_building(params) == 0 && BeingMapper.isCourests(params) == 0) {


                        params.put("CheckRealityTime", df.format(new Date()));
                        params.put("CheckState", 2);
                        if (BeingMapper.updateCheckState(params) > 0) {
                            params.put("State", 7);
                            housingauditfeign.updatehousingByHousId(params);//修改房源状态
                            movement(params);//如果这个房源验房全部通过了之后 把工程部里面的配置数据全部移到市场部的房源配置表里面去
                            if (BeingMapper.getCheckStateinfo(params) == 0) {
                                BeingMapper.updatedecorate_plan(params);//当着一批的所有房源全部完成之后自动的改变这个批次的状态
                                isSuccess = true;
                            }
                            //result.putSuccess("操作成功");
                        } else {
                            //  result.putFailed("操作失败");
                        }
                    }

                }
                result.putSuccess("操作成功");

            } else {
                result.putFailed("操作失败");

            }

        } else if ("3".equals(params.get("insexshow").toString())) {
            SimpleDateFormat df = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");//设置日期格式
            // new Date()为获取当前系统时间
            params.put("InspectTime", df.format(new Date()));
            params.put("by", ContextUtils.getUserId());//操作人
            params.put("term", "3");// 创建端 Insert端： 1 租客端 2市场部 3 工程部   4运营部   5财务部  6总经办 7发展部
            params.put("fnc", "updateInspectStateBy");// 创建Function名
            ParamsCommon.commonUpdateParms(params);
            if (mapper.updateInspectStateBySupType(params) > 0) {
                if ("2".equals(params.get("InspectState").toString())) {
                    params.put("IfCheckState", 1);
                    params.put("CheckStatus", 2);
                    mapper.updateIfCheckStatea(params);
                } else {

                    if (BeingMapper.countInspectState(params) == 0 && BeingMapper.countIfCheckState(params) == 0 && BeingMapper.plan_building(params) == 0) {
                        params.put("IfCheckState", 0);
                        params.put("CheckStatus", 3);
                        mapper.updateIfCheckStatea(params);

                    }

                    if (BeingMapper.countInspectState(params) == 0 && BeingMapper.countIfCheckState(params) == 0 && BeingMapper.plan_building(params) == 0 && BeingMapper.isCourests(params) == 0) {


                        params.put("CheckRealityTime", df.format(new Date()));
                        params.put("CheckState", 2);
                        if (BeingMapper.updateCheckState(params) > 0) {
                            params.put("State", 7);
                            housingauditfeign.updatehousingByHousId(params);//修改房源状态
                            movement(params);//如果这个房源验房全部通过了之后 把工程部里面的配置数据全部移到市场部的房源配置表里面去
                            if (BeingMapper.getCheckStateinfo(params) == 0) {
                                BeingMapper.updatedecorate_plan(params);//当着一批的所有房源全部完成之后自动的改变这个批次的状态
                                isSuccess = true;
                            }
                            //result.putSuccess("操作成功");
                        } else {
                            //  result.putFailed("操作失败");
                        }
                    }
                }
                result.putSuccess("操作成功");

            } else {
                result.putFailed("操作失败");

            }

        } else if ("4".equals(params.get("insexshow").toString())) {
            SimpleDateFormat df = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");//设置日期格式
            // new Date()为获取当前系统时间
            params.put("InspectTime", df.format(new Date()));
            params.put("by", ContextUtils.getUserId());//操作人
            params.put("term", "3");// 创建端 Insert端： 1 租客端 2市场部 3 工程部   4运营部   5财务部  6总经办 7发展部
            params.put("fnc", "updateInspectStateBy");// 创建Function名
            ParamsCommon.commonUpdateParms(params);
            if (mapper.updateInspectStateBySupType(params) > 0) {
                if ("2".equals(params.get("InspectState").toString())) {
                    params.put("IfCheckState", 1);
                    params.put("CheckStatus", 2);
                    mapper.updateIfCheckStatea(params);
                } else {

                    if (BeingMapper.countInspectState(params) == 0 && BeingMapper.countIfCheckState(params) == 0 && BeingMapper.plan_building(params) == 0) {
                        params.put("IfCheckState", 0);
                        params.put("CheckStatus", 3);
                        mapper.updateIfCheckStatea(params);

                    }

                    if (BeingMapper.countInspectState(params) == 0 && BeingMapper.countIfCheckState(params) == 0 && BeingMapper.plan_building(params) == 0 && BeingMapper.isCourests(params) == 0) {


                        params.put("CheckRealityTime", df.format(new Date()));
                        params.put("CheckState", 2);
                        if (BeingMapper.updateCheckState(params) > 0) {
                            params.put("State", 7);
                            housingauditfeign.updatehousingByHousId(params);//修改房源状态
                            movement(params);//如果这个房源验房全部通过了之后 把工程部里面的配置数据全部移到市场部的房源配置表里面去
                            if (BeingMapper.getCheckStateinfo(params) == 0) {
                                BeingMapper.updatedecorate_plan(params);//当着一批的所有房源全部完成之后自动的改变这个批次的状态
                                isSuccess = true;
                            }
                            //result.putSuccess("操作成功");
                        } else {
                            //  result.putFailed("操作失败");
                        }
                    }

                }
                result.putSuccess("操作成功");

            } else {
                result.putFailed("操作失败");

            }
        }

        if (MapUtils.getInteger(params, "InspectState").equals(2)) {
            //验房未通过
            String houId = mapper.getHouId((String) params.get("PlansId"));
            CustomMap data = CustomMap.create("MeType", 7)
                    .put("Title", "新接收的异常验房单")
                    .put("Content", HtmlUtil.stringToHTML("（" + houId + "）该房源配置验收不通过，请注意！；", houId, Color.blue))
                    .put("by", ContextUtils.getUserId())
                    .put("IfJump", 1)
                    .put("Neturl", "/sys-engineeringmanager/decorationmanagement")
                    .put("term", 3);
            feign.AddMessage(data);
        }


        if (isSuccess) {
            //装修计划完成了
            String plansId = mapper.getHouId((String) params.get("PlansId"));
            CustomMap data = CustomMap.create("MeType", 5)
                    .put("Title", "装修完成批次")
                    .put("Content", HtmlUtil.stringToHTML("(" + plansId + ")该批次装修计划已完成，点击查看费用详情；", plansId, Color.blue))
                    .put("by", ContextUtils.getUserId())
                    .put("IfJump", 1)
                    .put("Neturl", "/sys-engineeringmanager/decorationmanagement")
                    .put("term", 3);
            feign.AddMessage(data);
        }

        return result;
    }


    /**
     * 移动数据
     *
     * @param params
     */
    @Override
    public void movement(Map<String, Object> params) {
        Map<String, Object> reqMap = new HashMap<String, Object>();
        //首先先查询出来
        //先查询出 配置主表
        reqMap.put("HouingCon", mapper.getHouingCon(params));
        //查询出配置详表
        reqMap.put("HouingConInfo", mapper.getHouingConInfo(params));

        /**
         * 首先查询房源的房间号id
         */
        List<Map<String, Object>> hId = mapper.getHouingHouConId(params);
        /**
         * 查询出无线网络 电视
         */
        List<Map<String, Object>> configList = mapper.getHouingConInfoWiFi(params);

        List<Map<String, Object>> data = Lists.newArrayList();

        for (int i = 0; i < hId.size(); i++) {
            Map<String, Object> idItem = hId.get(i);
            for (int j = 0; j < configList.size(); j++) {
                Map<String, Object> conItem = configList.get(j);
                Map<String, Object> item = Maps.newHashMap(conItem);
                item.putAll(idItem);
                data.add(item);
            }
        }
        log.info("Result Data.size => {}", data.size());
        log.info("Result Data => {}", data);
        //无线网络电视
        reqMap.put("HouingConInfoWiFi", data);
        housingauditfeign.saveHousingCon(reqMap);//远程调用
    }

    @Override
    public JsonResult getArticleType(Map<String, Object> params) {
        JsonResult result = new JsonResult();
        result.put(mapper.getArticleType(params));
        return result;
    }

    @Override
    public JsonResult getarticle(Map<String, Object> params) {
        JsonResult result = new JsonResult();

        result.put(mapper.getarticle(params));

        return result;
    }

    @Override
    public JsonResult getArticleTrouble(Map<String, Object> params) {
        JsonResult result = new JsonResult();
        result.put(mapper.getArticleTrouble(params));
        return result;
    }

    @Override
    public JsonResult saveTepair(Map<String, Object> params) {
        JsonResult result = new JsonResult();

        log.info("params====>" + params);
        /**
         * 加锁操作
         */
        lock.lock();
        try {
            List<Map<String, Object>> houImgList = (List<Map<String, Object>>) params.get("TroubleFile");//首先获得这个集合
            StringBuffer KitchenFile = new StringBuffer();

            for (Map<String, Object> houimg : houImgList) {
                KitchenFile.append(houimg.get("url").toString() + ",");//追加字符串
            }
            KitchenFile.deleteCharAt(KitchenFile.length() - 1);//去除字符串最后一个逗号
            log.info("KitchenFile>>>>>>>>>=" + KitchenFile);
            params.put("TroubleFile", KitchenFile.toString());

            String UUID = null;
            Map<String, Object> uuid = utilsMapper.getUUID(new HashMap<String, Object>() {{
                put("uuid", "RepId");
                put("database", Constants.DATA_SOURCE_TCEPC);
                put("surface", "tcepc_repair");
            }});
            if (uuid != null) {
                int number = Integer.valueOf(uuid.get("uuid").toString());
                UUID = ComUtils.getLocalTrmSeqNum("Rep", number);
            } else {
                UUID = ComUtils.getLocalTrmSeqNum("Rep", 0);
            }
            params.put("RepId", UUID);
            String SysUserId = ContextUtils.getUserId();
            params.put("RepairsId", SysUserId);//报修人
            params.put("by", SysUserId);//操作人
            params.put("term", "3");// 创建端 Insert端： 1 租客端 2市场部 3 工程部   4运营部   5财务部  6总经办 7发展部
            params.put("fnc", this.getClass().getSimpleName() + "." + Thread.currentThread().getStackTrace()[1].getMethodName());// 创建Function名
            ParamsCommon.commonInsertParms(params);

            log.info("params=====>" + params);

            if (mapper.saveTepair(params) > 0) {
                result.putSuccess("操作成功!");
            } else {
                result.putFailed("操作失败");
            }

        } catch (Exception e) {
            result.putFailed("服务器繁忙...");
        } finally {
            lock.unlock();//解锁
        }

        return result;
    }

    /**
     * 方法暂时作废
     *
     * @param params
     * @param pager
     * @return
     */
    @Override
    public JsonResult getTepairByOrdState(Map<String, Object> params, Pager pager) {
        JsonResult result = new JsonResult();
        try {
            log.info("params=======>" + params);
            List<Map<String, Object>> dataLIst = mapper.getTepairByOrdState(params);
            List<Map<String, Object>> list = new ArrayList<Map<String, Object>>();
            List<String> usrlist;
            for (Map<String, Object> map : dataLIst) {//

                usrlist = new ArrayList<String>();//创建一个list的集合
                usrlist.add(map.get("RepairsId").toString());//获取报修人id;
                JsonResult<List<Map<String, Object>>> res = getUserInfoFeign.getUserInfo(usrlist);//获取用户集合
                List<Map<String, Object>> data = res.getResult();
                map.put("username", MapUtils.getString(data.get(0), "username")); //发起人id
                map.put("mobile", MapUtils.getString(data.get(0), "mobile"));//发起人手机号码
            }


        } catch (Exception e) {
            log.error("E>>>>" + e);
            result.putFailed("服务器繁忙...");
        }


        return result;
    }

    /**
     * 服务管家验房通过后修改状态为验房已经完成
     */
    @Transactional(rollbackFor = Exception.class)
    public JsonResult updateIfCheck(Map<String, Object> params) {
        JsonResult result = new JsonResult();
        /**
         * 加锁操作
         */
        lock.lock();
        try {
            try {
                if (params.get("PlansId") == null) {
                    log.info("缺少参数:PlansId");
                    return result.putFailed("缺少参数:PlansId");
                }
                params.put("IfUpload", 1);//验房通过之后是否已上传图片 0.否 1.是
                params.put("by", ContextUtils.getUserId());//操作人
                params.put("term", "4");// 创建端 Insert端： 1 租客端 2市场部 3 工程部   4运营部   5财务部  6总经办 7发展部
                params.put("fnc",
                        this.getClass().getSimpleName() + "." + Thread.currentThread().getStackTrace()[1].getMethodName());// 创建Function名
                ParamsCommon.commonUpdateParms(params);
                //修改房源主表图片
                Integer count = BeingMapper.updateIfCheckStateaHo(params);
                if (count > 0) {
                    result.putSuccess("操作成功");
                } else {
                    result.putFailed("操作失败");
                }
            } catch (Exception e) {
                e.printStackTrace();
                TransactionAspectSupport.currentTransactionStatus().setRollbackOnly();
            }
        } finally {
            lock.unlock();
        }
        return result;
    }
}
